import functools
import logging
import os
import yaml
from logging.config import dictConfig
from pydantic import BaseSettings
from utils.dom_xmlParse import ParseXml


class Settings(BaseSettings):
    ROOT_PATH = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

    OPEN_API_URL = os.path.join(ROOT_PATH, "docs", "api.yaml")

    COMMON_CONFIG_PATH = os.path.join(ROOT_PATH, "utils", "config_comm.xml")
    PROJECT_CONFIG_PATH = os.path.join(ROOT_PATH, "core", "project.yaml")
    LOGGER_CONFIG_PATH = os.path.join(ROOT_PATH, "core", "logger.yaml")
    ENV = "develop"

    class HTTP:
        host: str = "127.0.0.1"
        port = 8080

    class DB:
        KEYWORD = "homed_dtvs"
        host: str = "127.0.0.1"
        port: int = 3306
        user: str = "root"
        password: str = "As-000000"
        database: str = "homed_extapp"

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.__init_project_config()
        self.__init_common_config()
        self.__init_log_config()

    def __init_common_config(self):
        common_config_obj = ParseXml(self.COMMON_CONFIG_PATH)

        # ------------- db_config --------------
        if self.ENV == "production":
            print("解析 homed的db配置")
            db_config_dom = common_config_obj.get_child_nodes_from_node(
                "db_config"
            )
            if db_config_dom:
                db_config_dom = db_config_dom[0]
                db_ips = common_config_obj.parse_one_nodes_text("db_ip", db_config_dom)
                db_names = common_config_obj.parse_one_nodes_text("db_name", db_config_dom)
                db_user_names = common_config_obj.parse_one_nodes_text("db_username", db_config_dom)
                db_passwords = common_config_obj.parse_one_nodes_text("db_password", db_config_dom)
                db_ports = common_config_obj.parse_one_nodes_text("db_port", db_config_dom)
                for i, j in enumerate(db_names):
                    if j == self.DB.KEYWORD:
                        self.DB.database = "homed_extapp"
                        self.DB.host = db_ips[i]
                        self.DB.user = db_user_names[i]
                        self.DB.port = db_ports[i]
                        self.DB.password = db_passwords[i]

    def __init_project_config(self):
        with open(self.PROJECT_CONFIG_PATH, encoding="utf-8") as f:
            project_config = yaml.load(f, Loader=yaml.FullLoader)
        for key, value in project_config.items():
            if key == "Http":
                self.HTTP.host = value["host"]
                self.HTTP.port = int(value["port"])
            elif key == "Homed":
                self.DB.KEYWORD = value["db_keyword_in_homed"]
            else:
                setattr(self, key.upper(), value)

    def __init_log_config(self):
        with open(self.LOGGER_CONFIG_PATH, encoding="utf-8") as f:
            log_config: dict = yaml.load(f, Loader=yaml.FullLoader)
        for key, value in log_config.items():
            if key == "handlers":
                for i, j in value.items():
                    if "filename" in j:
                        j["filename"] = os.path.join(self.ROOT_PATH,
                                                     "log",
                                                     os.path.basename(j["filename"]))
        print(f"[production_config:Settings] log_config={log_config}")
        dictConfig(log_config)


@functools.lru_cache()
def get_setting():
    return Settings()


if __name__ == '__main__':
    s = get_setting()
    logger = logging.getLogger("Activity")
    logger.info(f"DB: {s.DB.host}, {s.DB.user}, {s.DB.password}")
    logger.info("Activity init success")
